package com.my.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.my.api.request.AppRequestHead;

public class RequestUtil {
	
	private static final Logger LOGGER = Logger.getLogger(RequestUtil.class);

	/**
	 * HTTP请求参数转化
	 * @param request
	 * @return
	 */
	public static HashMap<String, String> getRequestParams(HttpServletRequest request) {
		Map<String, String[]> srcParamMap = request.getParameterMap();
		HashMap<String, String> destParamMap = new HashMap<String, String>();
		for (String obj : srcParamMap.keySet()) {
			String[] values = srcParamMap.get(obj);
			if (values != null && values.length > 0) {
				destParamMap.put(obj, values[0]);
			} else {
				destParamMap.put(obj, null);
			}
		}
		return destParamMap;
	}
	
	/**
	 * 转化成APP请求头
	 * @param request
	 * @return
	 */
	public static AppRequestHead convertToAppRequestHead(HttpServletRequest request){
		//String app = request.getParameter("app");
		//String source = request.getParameter("source");
		String timestamp = request.getParameter("timestamp");
		String token = request.getParameter("token");

		return (StringUtils.isBlank(timestamp)||StringUtils.isBlank(token)) ? null: new AppRequestHead(timestamp, token);
	}

	/**
	 * 调用response输出相关的内容
	 * @param response
	 * @param obj
	 */
	public static  void responseOutWithJson(HttpServletResponse response,Object obj) {  
	    //将实体对象转换为JSON Object转换  
	    String ret = JSONObject.toJSONString(obj);  
	    response.setCharacterEncoding("UTF-8");  
	    response.setContentType("application/json; charset=utf-8");  
	    PrintWriter out = null;  
	    try {  
	        out = response.getWriter();  
	        out.append(ret);  
	        LOGGER.debug("调用response输出:"+ret+"\n");  
	    } catch (IOException e) {  
	    	LOGGER.info("调用response输出:"+ret+"错误",e);  
	    } finally {  
	        if (out != null) {  
	            out.close();  
	        }  
	    }
	} 
}
